package top.kaoshanji.p3ch11b;

import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 代码清单-p3ch11b-359页a：倒数闸门的使用示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/4 17:52
 */
public class PageSizeSorter {

    private static final Logger logger = LogManager.getLogger(PageSizeSorter.class);

    public static void main(String[] args) throws InterruptedException {
        logger.info("...代码清单-p3ch11b-359页a：倒数闸门的使用示例...");

        PageSizeSorter pso = new PageSizeSorter();
        List<String> urls = Arrays.asList(new String[]{
                "http://www.baidu.com",
                "http://www.sina.com.cn",
                "http://www.163.com"
        });
        pso.sortPageSize(urls);
    }


    private static final ConcurrentHashMap<String, Integer> sizeMap = new ConcurrentHashMap<>();

    public void sortPageSize(Collection<String> urls) throws InterruptedException {
        CountDownLatch sortSignal = new CountDownLatch(urls.size());
        for (String url: urls) {
            new Thread(new GetSizeWorker(url, sortSignal)).start();
        }

        sortSignal.await();
        sort();
    }

    private void sort() {
        List<Map.Entry<String, Integer>> list = new ArrayList<>(sizeMap.entrySet());
        list.sort(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return Integer.compare(o2.getValue(), o1.getValue());
            }
        });

        System.out.println(Arrays.deepToString(list.toArray()));
    }

    private static class GetSizeWorker implements Runnable {

        private final String urlString;
        private final CountDownLatch signal;

        public GetSizeWorker(String urlString, CountDownLatch signal) {
            this.urlString = urlString;
            this.signal = signal;
        }

        @Override
        public void run() {
            try {
                InputStream is = new URL(urlString).openStream();
                int size = IOUtils.toByteArray(is).length;
                sizeMap.put(urlString, size);
            } catch (IOException e) {
                sizeMap.put(urlString, -1);
            } finally {
                signal.countDown();
            }

        }
    }



}
